package blazingbubble.network.game.strategy;

import blazingbubble.game.Game;
import blazingbubble.game.Player;
import moltencore.network.protocol.PlayerJoinedGame;
import moltencore.network.protocol.PlayerJoinedTeam;
import org.apache.log4j.Logger;
import spark.network.protocol.Acknowledgement;
import spark.network.protocol.Base;
import spark.network.protocol.Response;
import spark.network.strategy.IProtocolHandleStrategy;
import spark.utility.OutWrapper;

import java.util.Collection;

public class PlayerJoinedTeamStrategy implements IProtocolHandleStrategy<PlayerJoinedTeam> {
	private Logger logger = Logger.getLogger(PlayerJoinedTeamStrategy.class);

	private Game game;
	private IPlayerTeamJoinListener playerTeamJoinListener;
	private PlayerTeamJoinBuffer playerTeamJoinBuffer;

	public PlayerJoinedTeamStrategy(Game game, IPlayerTeamJoinListener playerTeamJoinListener, PlayerTeamJoinBuffer playerTeamJoinBuffer) {
		this.game = game;
		this.playerTeamJoinListener = playerTeamJoinListener;
		this.playerTeamJoinBuffer = playerTeamJoinBuffer;
	}

	@Override
	public void handle(PlayerJoinedTeam packet, OutWrapper<Response> acknowledgement, Collection<Base> additionalData) {
		Player player = game.getPlayer(packet.getClientId());
		if(player != null) {
			player.setTeamIndex(packet.getTeamIndex());
			player.setPositionIndex(packet.getSlotIndex());
			playerTeamJoinListener.playerJoinedTeam(player);
		}
		// if the player has not been registered yet (packets arrived out of order) buffer the team join data
		// so it can be accessed when the player data arrives
		else {
			playerTeamJoinBuffer.buffer(packet.getClientId(), packet.getTeamIndex(), packet.getSlotIndex(), packet.getTimeStampSend());
		}
		acknowledgement.value = new Acknowledgement(packet);
	}
}